<template>
  <h1>管理员添加</h1>
  <el-form :model="admin">
    <el-form-item label="姓名" required>
      <el-input v-model="admin.adminname" />
    </el-form-item>

    <el-form-item label="密码" required>
      <el-input v-model="admin.password" type="password" placeholder="请输入密码" show-password />
    </el-form-item>

    <el-form-item label="角色" required>
      <el-radio-group v-model="admin.role">
        <el-radio :label="1">超级管理员</el-radio>
        <el-radio :label="2">普通管理员</el-radio>
      </el-radio-group>
    </el-form-item>
    <p>
      <el-tree ref="treeRef" :data="data" show-checkbox node-key="id" highlight-current />
    </p>

    <el-form-item>
      <el-button type="primary" @click="addadmin">添加</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import 'element-plus/dist/index.css'
import { ElMessage, ElTree } from 'element-plus';
import { reactive, ref } from 'vue'
import service from '../../../ulit/service'
import { useRouter } from "vue-router";
import { menudata as data } from "../../../grants/menudata"
import type { TreeKey } from "element-plus/es/components/tree/src/tree.type"
const $router = useRouter();

interface Iadmin {
  "password": string,
  "role": number//1:表示超级管理员，2：普通管理员
  "adminname": string,
  "checkedKeys": TreeKey[]
}
// 当前管理员的数据
const admin = reactive<Iadmin>({
  "password": '',
  "role": 1,//1:表示超级管理员，2：普通管理员
  "adminname": '',
  "checkedKeys": []
})
let treeRef = ref<InstanceType<typeof ElTree>>();
//添加功能 
const addadmin = () => {

  let arr: TreeKey[] = treeRef.value!.getCheckedKeys();//获取的是选中状态的菜单项。
  let halfArr: TreeKey[] = treeRef.value!.getHalfCheckedKeys();//获取半选中状态的菜单项。
  console.log("arr", arr);
  arr = arr.concat(halfArr)

  admin.checkedKeys = arr
  if (admin.password && admin.adminname) {
    service({
      url: "/admin/add",
      method: "post",
      data: admin
    }).then(res => {
      if (res.data.code === "200") {
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
        // admin.adminname = '',
        //   admin.password = '',
        //   admin.role = 0
        $router.push("adminlist")
      }
    })
  } else {
    ElMessage({
      message: '不能为空',
      type: 'error',
    })
    admin.adminname = '',
      admin.password = '',
      admin.role = 0
  }

}
</script>

<style scoped>
.el-form {
  margin: 80px 0 0 200px;

}

.el-input {
  width: 600px;
}
</style>